package com.zd.springcloud.tx;

import com.zd.springcloud.tx.mapper.AdminMapper;
import com.zd.springcloud.tx.mapper.UserMapper;
import com.zd.springcloud.tx.util.FactoryUtil;
import com.zd.springcloud.tx.util.SeataFactoryUtil;
import io.seata.rm.RMClient;
import io.seata.tm.TMClient;
import io.seata.tm.api.GlobalTransaction;
import io.seata.tm.api.GlobalTransactionContext;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

/**
 * 使用seata 解决mybatis项目的分布式事务问题
 */
public class MybatisShiWuSeata {

    static {
        String applicationId = "abc";
        String groupName = "default_tx_group";
        //初始化 TM
        TMClient.init(applicationId,groupName);


        //初始化 RM
        RMClient.init(applicationId,groupName);
    }

    public static void main(String[] args) throws Exception{




        SqlSessionFactory aaaSqlSessionFactory = SeataFactoryUtil.getAAASqlSessionFactory();



        SqlSessionFactory bbbSqlSessionFactory = SeataFactoryUtil.getBBBSqlSessionFactory();

        SqlSession aaaSqlSession = null;
        SqlSession bbbSqlSession = null;

        GlobalTransaction tx = GlobalTransactionContext.getCurrentOrCreate();

        //开启全局事务
        tx.begin();

        try{
            //王五减钱
            aaaSqlSession = aaaSqlSessionFactory.openSession(true);
            aaaSqlSession.getMapper(AdminMapper.class).reduceMoney(100.00);


            //int i = 10 / 0;
            //赵六加钱
            bbbSqlSession = bbbSqlSessionFactory.openSession(true);
            bbbSqlSession.getMapper(UserMapper.class).addMoney(100.00);

            /////提交事务
            tx.commit();

        }catch (Exception e){
            e.printStackTrace();
            tx.rollback();
        }finally {
            aaaSqlSession.close();
            bbbSqlSession.close();
        }


    }
}
